package com.yuji.aacar.controller.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yuji.aacar.R;
import com.yuji.aacar.base.BaseFragment;
import com.yuji.aacar.base.BaseFragmentActivity;
import com.yuji.aacar.base.EventConst;
import com.yuji.aacar.bean.response.VersionResponse;
import com.yuji.aacar.controller.fragment.home.HomeFragment;
import com.yuji.aacar.controller.fragment.mine.MineFragment;
import com.yuji.aacar.controller.fragment.order.OrderFragment;
import com.yuji.aacar.controller.splash.SplashActivity;
import com.yuji.aacar.core.cores.event.CoreEventBusMessage;
import com.yuji.aacar.core.cores.event.CoreEventCenter;
import com.yuji.aacar.core.cores.services.CoreServiceResponse;
import com.yuji.aacar.service.BaseServiceMediator;
import com.yuji.aacar.service.BaseServiceParams;
import com.yuji.aacar.widgets.autolayout.AutoLinearLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * <li>Package:com.yuji.aacar.controller.main</li>
 * <li>Author: lining </li>
 * <li>Date: 2018/2/28</li>
 * <li>Description:   </li>
 */

public class TabHomeActivity extends BaseFragmentActivity {

    public static final int HOME = 0;//首页
    public static final int ORDER = 1;//订单
    public static final int MINE = 2;//我的
    @BindView(R.id.tab_fragment_container)
    RelativeLayout tabFragmentContainer;
    @BindView(R.id.tab_fragment_home)
    TextView tabFragmentHome;
    @BindView(R.id.tab_fragment_sell)
    TextView tabFragmentSell;
    @BindView(R.id.tab_fragment_schedule)
    TextView tabFragmentSchedule;
    @BindView(R.id.tab_layout)
    AutoLinearLayout tabLayout;

    private Fragment currentFragment;
    private List<Fragment> tabs = new ArrayList<>();
    private String toPage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        setHomePageAndExitApp(true);
        toPage = getIntent().getStringExtra("page");
        initFragments();
        setTabTag();
        if (null != toPage && toPage.contentEquals("order")){
            changeFragment(ORDER);
        } else {
            changeFragment(HOME);
        }
    }

    @Override
    public void alreadyBindBaseViewModel() {
        super.alreadyBindBaseViewModel();
        requestVersionCheck();
    }

    private void initFragments() {
        HomeFragment sellCarFragment = (HomeFragment) getSupportFragmentManager().findFragmentByTag(HomeFragment.class.getName());
        OrderFragment valuationFragment = (OrderFragment) getSupportFragmentManager().findFragmentByTag(OrderFragment.class.getName());
        MineFragment personalFragment = (MineFragment) getSupportFragmentManager().findFragmentByTag(MineFragment.class.getName());

        initTabs(sellCarFragment, HomeFragment.class.getName());
        initTabs(valuationFragment, OrderFragment.class.getName());
        initTabs(personalFragment, MineFragment.class.getName());
    }

    private void initTabs(Fragment fragment, String fname) {
        if (fragment != null) {
            tabs.add(fragment);
        } else {
            tabs.add(Fragment.instantiate(this, fname));
        }
    }

    private void setTabTag() {
        for (int i = 0; i < tabLayout.getChildCount(); i++) {
            tabLayout.getChildAt(i).setTag(tabLayout.indexOfChild(tabLayout.getChildAt(i)));
        }
    }

    public void changeFragment(int index) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        initViewAndFragment(ft);
        tabLayout.getChildAt(index).setSelected(true);
        if (!tabs.get(index).isAdded()) {
            ft.add(R.id.tab_fragment_container, tabs.get(index), tabs.get(index).getClass().getName());
        }
        ft.show(tabs.get(index));
        ft.commitAllowingStateLoss();
        currentFragment = tabs.get(index);
        if (currentFragment instanceof BaseFragment){
            ((BaseFragment) currentFragment).showFragemt();
        }
    }

    private void initViewAndFragment(android.support.v4.app.FragmentTransaction ft) {
        for (int i = 0; i < tabLayout.getChildCount(); i++) {
            tabLayout.getChildAt(i).setSelected(false);
            ft.hide(tabs.get(i));
        }
    }

    @OnClick({R.id.tab_fragment_container, R.id.tab_fragment_home, R.id.tab_fragment_sell, R.id.tab_fragment_schedule, R.id.tab_layout})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tab_fragment_container:
                break;
            case R.id.tab_fragment_home:
                changeFragment((Integer) view.getTag());
                break;
            case R.id.tab_fragment_sell:
                changeFragment((Integer) view.getTag());
                break;
            case R.id.tab_fragment_schedule:
                changeFragment((Integer) view.getTag());
                break;
            case R.id.tab_layout:
                break;
        }
    }


    @Override
    public void handleMessage(CoreEventBusMessage message) {
        super.handleMessage(message);
        if (message.getMessageCode().contentEquals(EventConst.LOGIN_OUT+"")){
            this.finish();
            Intent startIntent = new Intent(getApplicationContext(),
                    SplashActivity.class);
            startActivity(startIntent);
        } else if (message.getMessageCode().contentEquals(String.valueOf(EventConst.PAY_FINISH))){
            changeFragment(ORDER);
        } else if (message.getMessageCode().contentEquals(String.valueOf(EventConst.RELOGIN))) {
            this.finish();
        }
    }

    public void requestVersionCheck(){
        requestParams = BaseServiceParams.compareAppVersion();
        doTask(BaseServiceMediator.COMPARE_APP_VERSION);
    }

    @Override
    public void requestSuccess(CoreServiceResponse response) {
        super.requestSuccess(response);
        if (response.getRequestCode() == BaseServiceMediator.COMPARE_APP_VERSION_CODE) {
            VersionResponse logOutResponse = (VersionResponse) response.getResponse();
            if (logOutResponse.getFlag().contentEquals("1")) {
                CoreEventCenter.postObject(EventConst.VERSION_UPDATE,logOutResponse);
            }
        }
    }

    @Override
    public void requestFailed(CoreServiceResponse response) {
        super.requestFailed(response);
    }
}
